package com.cloudwise.isop.kg.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import org.activiti.spring.SpringAsyncExecutor;
import org.activiti.spring.SpringProcessEngineConfiguration;
import org.activiti.spring.boot.AbstractProcessEngineAutoConfiguration;
import org.activiti.spring.boot.ActivitiProperties;
import org.activiti.spring.boot.DataSourceProcessEngineAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.io.IOException;

/**
 * 替代JpaProcessEngineAutoConfiguration, 替换activiti数据源
 *
 * @author lee
 * @see org.activiti.spring.boot.JpaProcessEngineAutoConfiguration
 */
@Configuration
@AutoConfigureBefore(DataSourceProcessEngineAutoConfiguration.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class JpaProcessEngineConfiguration {

    @Configuration
    @ConditionalOnClass(name = "javax.persistence.EntityManagerFactory")
    @EnableConfigurationProperties(ActivitiProperties.class)
    public static class JpaConfig extends AbstractProcessEngineAutoConfiguration {

        @Resource
        private DataSource dataSource;

        @Bean
        public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
            return new JpaTransactionManager(emf);
        }

        @Bean
        public SpringProcessEngineConfiguration springProcessEngineConfiguration(EntityManagerFactory entityManagerFactory,
                                                                                 PlatformTransactionManager transactionManager,
                                                                                 SpringAsyncExecutor springAsyncExecutor) throws IOException {
            DataSource activitiDataSource = ((DynamicRoutingDataSource) dataSource).getDataSource("activiti");
            SpringProcessEngineConfiguration config = this.baseSpringProcessEngineConfiguration(activitiDataSource,
                    transactionManager, springAsyncExecutor);
            config.setJpaEntityManagerFactory(entityManagerFactory);
            config.setTransactionManager(transactionManager);
            config.setJpaHandleTransaction(false);
            config.setJpaCloseEntityManager(false);
            return config;
        }
    }
}
